 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : KindlePush
 * Package  : net.solosky.kindlepush.action
 * File     : ForumAction.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : 2012-4-22
 * License  : Apache License 2.0 
 */
package net.solosky.kindlepush.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.solosky.kindlepush.forum.bean.Page;
import net.solosky.kindlepush.forum.bean.Post;
import net.solosky.kindlepush.forum.bean.Topic;
import net.solosky.kindlepush.forum.book.BookBuilder;
import net.solosky.kindlepush.forum.book.BookBuilderFactory;
import net.solosky.kindlepush.forum.provider.ForumProvider;
import net.solosky.kindlepush.forum.provider.ForumProviderFactory;
import net.solosky.kindlepush.util.MailUtils;

import org.nutz.mvc.annotation.At;

/**
 *
 * 论坛推送接口
 *
 * @author solosky <solosky772@qq.com>
 *
 */
@At("/forum")
public class ForumAction {
	@At
	public Topic topic(String url) throws Exception{
		ForumProvider provider = ForumProviderFactory.create(url);
		return provider.parseTopic(url);
	}
	
	@At
	public List<Post> posts(String url) throws Exception{
		ForumProvider provider = ForumProviderFactory.create(url);
		return provider.parsePosts(url);
	}
	
	@At
	public String push(final String url,final String email, final String bookType, final ServletContext context , 
			final HttpServletRequest request, final HttpSession session){
		
		String requestUrl = request.getRequestURL().toString();
		String servletPath = request.getServletPath();
		final String appUrl = requestUrl.substring(0, requestUrl.indexOf(servletPath));
		
		session.setAttribute("progress", "0|准备中..");
		session.removeAttribute("cancel");
		
		new Thread(new Runnable(){
			public void run(){
				try {
					session.setAttribute("progress", "0|获取帖子信息..");
					ForumProvider provider = ForumProviderFactory.create(url);
					Topic topic = provider.parseTopic(url);
					
					List<Page> lzPages = new ArrayList<Page>();
					List<Page> fltPages = new ArrayList<Page>();
					
					int floor = 1;
					int index = 1;
					
					int total = topic.getPageUrls().size();
					for(String u: topic.getPageUrls()){
						if(session.getAttribute("cancel")!=null){
							session.setAttribute("progress","100|用户取消操作");
							session.removeAttribute("cancel");
							return;
						}
						session.setAttribute("progress", Math.round(index/(float)total*90)+"|获取第"+index+"/"+total+"页帖子内容..");
						
						List<Post> posts = null;
						try {
							posts = provider.parsePosts(u);
						} catch (IOException e) {
							posts = provider.parsePosts(u);
						}
						
						List<Post> lzPosts = new ArrayList<Post>();
						List<Post> fltPosts = new ArrayList<Post>();
						
						for(Post post: posts){
							post.setFloor(++floor);
							if(post.getAuthor().equals(topic.getAuthor())){
								lzPosts.add(post);
							}
							if(post.getText().length()>20){
								fltPosts.add(post);
							}
						}
						
						lzPages.add(new Page(index, lzPosts));
						fltPages.add(new Page(index, fltPosts));
						index++;
					}
					
					session.setAttribute("progress", "95|生成电子书中..");
					
					BookBuilder builder = BookBuilderFactory.create(bookType); 
					builder.writeTopic("书籍封面", topic);
					for(Page page: fltPages){
						builder.writePosts("帖子正文", "帖子第"+page.getPage()+"页", page.getPosts());
					}
					for(Page page: lzPages){
						builder.writePosts("只看楼主", "帖子第"+page.getPage()+"页", page.getPosts());
					}
					boolean needPush = email!=null && email.indexOf("@")!=-1;
					//String bookName = System.currentTimeMillis()+"."+bookType;
					String bookName = (needPush ? topic.getTitle() : System.currentTimeMillis())+"."+bookType;
					File bookDir = new File(context.getRealPath("/books"));
					if(!bookDir.exists()){
						bookDir.mkdirs();
					}
					File bookFile = new File(context.getRealPath("/books")+"/"+bookName);
					builder.saveBook(bookFile);
					if(needPush){
						session.setAttribute("progress", "98|正在推送到邮箱"+email+"中,请稍后...");
						MailUtils.sendKindleEmail(email, bookFile);
						session.setAttribute("progress", "100|已经推送到邮箱"+email+"中, 请稍后查收。");
					}else{
						session.setAttribute("progress", "100|生成电子书成功，地址是:"+appUrl+"/books/"+bookName);
					}
					
				} catch (Exception e) {
					session.setAttribute("progress", "100|推送过程出错，请重试, 错误信息:"+e.getMessage());
				}
			}
		}).start();
		return "OK";
	}
	
	@At
	public Object progress(HttpSession session){
		Map<String,String> map = new HashMap<String, String>();
		String progress = (String) session.getAttribute("progress");
		if(progress!=null){
			String[] pairs = progress.split("\\|");
			map.put("progress", pairs[0]);
			map.put("msg", pairs[1]);
		}else{
			map.put("progress", "0");
			map.put("msg", "无提交操作！！");
		}
		return map;
	}
	
	@At
	public String cancel(HttpSession session){
		session.setAttribute("cancel", new Boolean(true));
		return "OK";
	}
}
